<template>
	<div id="removeDialogContainer">
		<el-dialog
			v-model="privateConfig.visible"
			:title="confirmDialogConfig.title"
			:width="props.width"
			align-center
			:close-on-click-modal="false"
			:show-close="false"
			:close-on-press-escape="false"
			:before-close="props.beforeClose"
			@close="props.beforeClose"
		>
			<!-- 如果没有传递插槽, 则使用传递的变量内容 -->
			<slot>
				<div>{{ confirmDialogConfig.content }}</div>
			</slot>

			<template #footer>
				<div class="dialog-footer">
					<el-button :loading="privateConfig.loading" @click="cancel">取消</el-button>
					<el-button :loading="privateConfig.loading" type="primary" @click="confirm">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, nextTick } from "vue";

const props = defineProps({
	width: { type: String, default: "500px" },
	beforeClose: {
		type: Function,
		default: () => {},
	},
});

const params = {
	title: "", // 标题
	content: "", // 内容_也可以为组件传递插槽[slot=content]
	isAsync: false, // 是否异步关闭弹窗
	cancel: () => {}, // 取消回调
	confirm: () => {}, // 确定回调
	openAfter: () => {}, // 打开后回调_如果在编辑时需要对表单赋值, 需要在该时机里复制, 否则会发生关闭后再打开弹窗展示的是上一次的数据
};

// 确认弹窗配置
const confirmDialogConfig = ref({ ...params });
// 私有配置
const privateConfig = ref({
	visible: false, // 是否展示
	loading: false, // 如果是异步, 点击确认时需要开启按钮加载, 防止重复点击
});

// 取消
const cancel = () => {
	confirmDialogConfig.value = { ...params };

	privateConfig.value.visible = false;
	confirmDialogConfig.value.cancel();
};
// 确定
const confirm = () => {
	// 如果是异步, 则会传递一个关闭函数
	if (confirmDialogConfig.value.isAsync) {
		privateConfig.value.loading = true;

		confirmDialogConfig.value.confirm({
			// 只关闭loading
			stopLoading: () => {
				privateConfig.value.loading = false;
			},
			// 关闭loading且关闭弹窗
			done: () => {
				confirmDialogConfig.value = { ...params };

				privateConfig.value.visible = false;
				privateConfig.value.loading = false;
			},
		});

		return;
	}

	confirmDialogConfig.value.confirm();
	cancel(false);
};

// 打开弹窗
const open = (config) => {
	privateConfig.value.visible = true;

	nextTick(() => {
		confirmDialogConfig.value = { ...params, ...config };
		if (config.openAfter) config.openAfter();
	});
};
defineExpose({ open });
</script>

<style scoped lang="scss"></style>
